package com.wuhao.shootclient.ui.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import com.wuhao.shootclient.util.UIUtil;


/**
 * Created by huangmeng1 on 2018/3/7.
 */

public class DragLayout extends RelativeLayout {

    private int movex;
    private int movey;
    private int dx;
    private int dy;
    private int left ;
    private int top  ;
    private int right ;
    private int bottom ;
    private int screenHeight;

    public DragLayout(Context context) {
        this(context,null);
    }

    public DragLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        screenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
    }


    private int lastX;
    private int lastY;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (left!=0 || top!=0 || bottom!=0 || right!=0){
            layout(left, top, right, bottom);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                movex = lastX;
                movey = lastY;
                break;
            case MotionEvent.ACTION_MOVE:
                dx = (int) event.getRawX() - lastX;
                dy = (int) event.getRawY() - lastY;

                 left = getLeft() + dx;
                 top = getTop() + dy;
                 right = getRight() + dx;
                 bottom = getBottom() + dy;
                if (left < 0) {
                    left = 0;
                    right = left + getWidth();
                }
                if (right >  UIUtil.getScreenWidth(getContext())) {
                    right =  UIUtil.getScreenWidth(getContext());
                    left = right - getWidth();
                }
                if (top < 0) {
                    top = 0;
                    bottom = top + getHeight();
                }

                if (bottom > screenHeight) {

                    bottom = screenHeight;
                    top = bottom - getHeight();
                }
                layout(left, top, right, bottom);
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_UP:
                if ((int) (Math.abs(event.getRawX() - movex)) >= 10 ||
                        (int) (Math.abs(event.getRawY() - movey)) >= 10) {
                    return true;
                } else {
                    return performClick();
                }
            default:
                break;
        }
        return super.onTouchEvent(event);
    }
}
